//
//  HttpUtil.swift
//  ios_swift_demo1
//
//  Created by liutao on 2020/7/15.
//  Copyright © 2020 lt. All rights reserved.
//

import UIKit
//json转model
import HandyJSON
//加载弹窗
import MBProgressHUD
import Moya


let LoadingPlugin = NetworkActivityPlugin { (type, target) in
    //获取当前的控制器
    guard let vc = topVC else { return }
    switch type {
    case .began:
        MBProgressHUD.hide(for: vc.view, animated: false)
        MBProgressHUD.showAdded(to: vc.view, animated: true)
    case .ended:
        MBProgressHUD.hide(for: vc.view, animated: true)
    }
}

//超时关闭
let timeoutClosure = {(endpoint: Endpoint, closure: MoyaProvider<BaseApiConfig>.RequestResultClosure) -> Void in
    
    if var urlRequest = try? endpoint.urlRequest() {
        urlRequest.timeoutInterval = 20
        closure(.success(urlRequest))
    } else {
        closure(.failure(MoyaError.requestMapping(endpoint.url)))
    }
}

//初始化一个moya
let BaseApiProvider = MoyaProvider<BaseApiConfig>(requestClosure:timeoutClosure)

//带加载圈的moya
let BaseLoadingApiProvide = MoyaProvider<BaseApiConfig>(requestClosure:timeoutClosure,plugins:[LoadingPlugin])




//请求分类
enum BaseApiConfig {
    //相关搜索
    case searchRelative(inputText: String)
    //分类列表
    case cateList
    
}

//网络请求配置
extension BaseApiConfig : TargetType {
    var baseURL: URL {
        return URL(string: "http://app.u17.com/v3/appV3_3/ios/phone")!
    }
    
    //路径
    var path: String {
        switch self {
        case .searchRelative: return "search/relative"
        case .cateList: return "sort/mobileCateList"
        }
    }
    
    //请求类型
    var method: Moya.Method {
        return .get
    }
    
    
    
    //请求任务事件，附带上请求的参数
    var task: Task {
        var parmeters : [String:Any] = [:]
        switch self {
            
        case .searchRelative(let inputText):parmeters["inputText"] = inputText
            
        default: break
        }
        
        return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
    }
    
    //请求头
    var headers: [String : String]? {
        return nil
    }
    
    //这个就是做单元测试模拟的数据，只会在单元测试文件中有作用
    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    
}


extension Response {
    func mapModel<T:HandyJSON>(_ type:T.Type) throws -> T {
        let jsonString = String(data: data, encoding: .utf8)
        guard let model = JSONDeserializer<T>.deserializeFrom(json: jsonString) else {
            throw MoyaError.jsonMapping(self)
        }
        return model
    }
}

extension MoyaProvider{
//    open func request(_ target: Target,
//                      callbackQueue: DispatchQueue? = .none,
//                      progress: ProgressBlock? = .none,
//                      completion: @escaping Completion) -> Cancellable {
//
//        let callbackQueue = callbackQueue ?? self.callbackQueue
//        return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion)
//    }
     @discardableResult
    open func request<T: HandyJSON>(_ target: Target,
                                    model: T.Type,
                                    completion: ((_ returnData: T?) -> Void)?) -> Cancellable? {
        return request(target, completion: { (result) in
            guard let completion = completion else { return }
         
            guard let returnData = try? result.value?.mapModel(LBUResponseData<T>.self) else {
                completion(nil)
                return
            }
            print("这里打印请求的数据结果\(String(describing: returnData.data))")
            completion(returnData.data?.returnData)
        })
    }
   
   
}

